package xxy.com.yangproject.ui.fragment;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.activity.OnBackPressedDispatcher;
import androidx.activity.OnBackPressedDispatcherOwner;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelStore;
import androidx.lifecycle.ViewModelStoreOwner;
import androidx.paging.PagedList;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;

import java.util.Locale;

import me.jessyan.autosize.AutoAdaptStrategy;
import me.jessyan.autosize.AutoSize;
import me.jessyan.autosize.AutoSizeConfig;
import me.jessyan.autosize.external.ExternalAdaptInfo;
import me.jessyan.autosize.internal.CancelAdapt;
import me.jessyan.autosize.internal.CustomAdapt;
import me.jessyan.autosize.utils.AutoSizeUtils;
import xxy.com.yangproject.R;
import xxy.com.yangproject.database.Entity.Cheese;
import xxy.com.yangproject.database.viewmodel.CheeseViewModel;
import xxy.com.yangproject.ui.view.DataBaseAdapter;

public class NavigationThirdFragment extends Fragment implements CustomAdapt , CancelAdapt {

    private Context mContext;
    private RecyclerView recyclerView;
    private ImageView imageView;
    private Button button;
    private EditText etDatabse;
    private DataBaseAdapter dataBaseAdapter;
    private CheeseViewModel cheeseViewModel;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewDataBinding viewDataBinding = DataBindingUtil.inflate(inflater, R.layout.frag_navigation_third, container, false);

        return viewDataBinding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mContext = getContext();
        //recyclerview & database
        recyclerView = view.findViewById(R.id.rv_database);
        imageView = view.findViewById(R.id.iv_frag_third);
        button = view.findViewById(R.id.bt_database);
        etDatabse = view.findViewById(R.id.et_database);
        dataBaseAdapter = new DataBaseAdapter();
        recyclerView.setAdapter(dataBaseAdapter);
//        new thesms.com.myapplication.mainactivity();
        ViewModelProvider viewModelProvider = new ViewModelProvider(new ViewModelStoreOwner() {
            @NonNull
            @Override
            public ViewModelStore getViewModelStore() {
                return null;
            }
        });
        cheeseViewModel = viewModelProvider.get(CheeseViewModel.class);
        cheeseViewModel.livePagedList.observe(null, new Observer<PagedList<Cheese>>() {
            @Override
            public void onChanged(PagedList<Cheese> cheeses) {
                dataBaseAdapter.submitList(cheeses);
            }
        });
        initListener();
        initSwipeToDelete();
    }

    private void initSwipeToDelete() {
        new ItemTouchHelper(new ItemTouchHelper.Callback() {
            @Override
            public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
                return makeMovementFlags(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT);
            }

            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
//                if () {
//
//                }
            }
        });
    }

    private void initListener() {
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addCheese();
            }
        });

        //editText
        etDatabse.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {   //typically meaning there is nothing more to input and the  IME will be closed
                    addCheese();
                    return true;
                }
                return false;
            }
        });

        etDatabse.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                //ACTION_DOWN  KEYCODE_ENTER
                if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
                    addCheese();
                    return true;
                }
                return false;
            }
        });
    }

    //数据库添加数据，页面刷新
    private void addCheese() {
        String cheese = etDatabse.getText().toString().trim();
        if (!TextUtils.isEmpty(cheese)) {
            //use viewmodel to do insert operation
            cheeseViewModel.insert(cheese);
            etDatabse.setText("");
        }
    }

    //是否按照宽度进行等比例适配 (为了保证在高宽比不同的屏幕上也能正常适配, 所以只能在宽度和高度之中选一个作为基准进行适配)
    //
    @Override
    public boolean isBaseOnWidth() {
        AutoSizeUtils.dp2px(mContext, 2f);
        return false;
    }

    @Override
    public float getSizeInDp() {
        return 0;
    }

    //屏幕密度自定义策略
    private class MyStrategy implements AutoAdaptStrategy {

        //对应不同的适配方案作出策略
        @Override
        public void applyAdapt(Object target, Activity activity) {
            //检查是否开启了外部三方库的适配模式, 只要不主动调用 ExternalAdaptManager 的方法, 下面的代码就不会执行
            if (AutoSizeConfig.getInstance().getExternalAdaptManager().isRun()) {
                //这个 {@link Activity} 是否存在在取消适配的列表中, 如果在, 则该 {@link Activity} 适配失效
                if (AutoSizeConfig.getInstance().getExternalAdaptManager().isCancelAdapt(target.getClass())) {
                    //delete this activity
                    AutoSize.cancelAdapt(activity);
                } else {   //不存在在取消适配的列表中
                    //得到额外适配活动信息
                    ExternalAdaptInfo info =  AutoSizeConfig.getInstance().getExternalAdaptManager().getExternalAdaptInfoOfActivity(target.getClass());
                    if (info != null) {
                        //使用外部三方库的 {@link Activity} 或 Fragment 的自定义适配参数进行适配
                        AutoSize.autoConvertDensityOfExternalAdaptInfo(activity, info);
                        return;
                    }
                }
            }

            //如果 target 实现 CancelAdapt 接口表示放弃适配, 所有的适配效果都将失效
            if (target instanceof CancelAdapt) {
                //取消适配
                AutoSize.cancelAdapt(activity);
                return;
            }

            //如果 target 实现 CustomAdapt 接口表示该 target 想自定义一些用于适配的参数, 从而改变最终的适配效果
            if (target instanceof CustomAdapt) {
                //使用 {@link Activity} 或 Fragment 的自定义参数进行适配
                AutoSize.autoConvertDensityOfCustomAdapt(activity, (CustomAdapt) target);
            } else {
                //自动转换全局密度
                AutoSize.autoConvertDensityOfGlobal(activity);
                LogUtils.e(String.format(Locale.ENGLISH, "%s used the global configuration.", target.getClass().getName()));
            }
        }
    }

}
